import {
  defineStore
} from 'pinia'
import {
  get,
  wxLogin,
  toast,
  getUrlParam,
  delUrlParam,
  randomStr
} from '../utils/helper.js'
import {
  isWx
} from '../utils/is.js'
const user = defineStore({
  id: 'user',
  state: () => ({
    isReady: null,
    onReady: null,
    isLogin: !!uni.getStorageSync('token'), // 登录状态
    info: {}, // 用户信息
    wxInfo: uni.getStorageSync('wxInfo') || {},
    isWxLogin: !!uni.getStorageSync('wxId'),
    authType: '',
    agent: {}
  }),
	
  getters: {
    agentId: (state) => state.agent?.id ?? 0
  },

  actions: {
    /**
		 * pinia-user 初始化
		 */
    async init() {
      if (!this.isWxLogin) {
        let client = 0
        let code = ''
        // #ifdef MP
        const miniRes = await wxLogin()
        client = 1
        code = miniRes.code
        // #endif
				
        // #ifdef H5
        if (getUrlParam('state', 'null') === uni.getStorageSync('wxRedirectState') && getUrlParam('code')) {
          uni.removeStorageSync('wxRedirectState')
          code = getUrlParam('code')
        } else if (isWx()) {
          // 第一次进入项目
          const wxRedirectState = randomStr(6)
          uni.setStorageSync('wxRedirectState', wxRedirectState)
          const scope = 'snsapi_base' // snsapi_userinfo=高级授权； snsapi_base=静默授权
          const redirectUri = delUrlParam(window.location.href, ['code', 'state', 'reduri'])
          const appid = 'wx0492d2cbed35043e'
          // 平台用的是公共域名，无需跳转APP_HOST下授权
          let authorUrl =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(redirectUri)}&response_type=code&scope=${scope}&state=${wxRedirectState}#wechat_redirect`
          // 重定向到微信授权
          window.location.replace(authorUrl)
          return Promise.reject('未登录')
        }
        // #endif
        if (code) {
          const [authErr, authRes] = await get('/index/wxAuth', { code, client }, { isAsync: 1 })
          if (authErr) {
            return toast(authErr.msg)
          }
          if (authRes.data.nickname) {
            this.setWxInfo(authRes.data)
          } else {
            this.setWxLogin(authRes.data.wxId)
          }
        }
      }
      if (this.isLogin) {
        await Promise.all([this.getInfo(), this.getAgent()])
      } else {
        // uni.reLaunch({
        //   url: '/pages/index/login'
        // })
        return Promise.reject('未登录')
      }
      if (this.onReady === 'function') {
        this.onReady()
      }
      return {
        agent: this.agent
      }
    },
		
    setWxLogin(value = '') {
      uni.setStorageSync('wxId', value)
      this.isWxLogin = true
      return { value }
    },
		
    setWxInfo(value = '') {
      uni.setStorageSync('wxId', value.id || value.wxId)
      this.isWxLogin = true
			
      uni.setStorageSync('wxInfo', value)
      this.wxInfo = value
    },
		
    /**
		 * pinia-user 设置 token
		 */
    async setToken(value = '') {
      uni.setStorageSync('token', value)
      this.isLogin = true
      const agent = await this.getAgent()
      return {
        token: value,
        agent
      }
    },
    /**
		 * pinia-user 清除 token
		 */
    clearToken() {
      uni.removeStorageSync('token')
      this.isLogin = false
      this.agent = {}
    },
		
    // 获取设备信息
    async getAgent(id) {
      const res = await get('/user/agentInfo', { id })
      this.agent = res.success ? res.data : {}
      return this.agent
    },
		
    /**
		 * pinia-user 获取个人信息
		 */
    async getInfo() {
      const [err, res] = await get('/user/info', {}, {
        isAsync: true
      })
      if (err) {
        return Promise.reject({
          msg: err.msg
        })
      }
      this.info = res.data

      return res.data
    },
    /**
		 * pinia-user 登出
		 */
    async logout(force = false) {
      this.clearToken()
    },

    setAuthType(value = '') {
      this.authType = value
    }
  }
})

export default user
